package com.atom.app.mvi.ui.compose.view

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.material3.AlertDialog
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.FirstBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.atom.app.mvi.ui.compose.view.text_icon.TextIcon
import com.atom.module.logger.Logger

class MenuActivity : ComponentActivity() {


    sealed class Routers(val router: String, val descriptor: String = "") {
        companion object {
            fun getRouters() = mutableListOf(
                Main,
                Simple,
                Simple1,
                Simple2,
                CustomView,
                CustomLayout,
                Spannable,
                Combined,
                Dialog
            )

            fun getRoutersFilterMain(): List<Routers> {
                val routers = getRouters()
                val mutableListOf: MutableList<Routers> = mutableListOf(* routers.toTypedArray())
                mutableListOf.remove(Main)
                return mutableListOf
            }

            fun getMainRouter() = Main.router

        }

        @Composable
        abstract fun RouterLayout(
            activity: ComponentActivity,
            nav: NavHostController,
            entry: NavBackStackEntry
        )

        object Main : Routers("main") {

            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                val routers = getRoutersFilterMain()
                val rowSize = 5
                val columnSize =
                    (routers.size / (rowSize - 1)) + (if (routers.size % (rowSize - 1) == 0) 0 else 1)
                LazyColumn(modifier = Modifier.fillMaxSize()) {
                    items(columnSize) { item ->

                        // 创建一个对应的icon 和 下面的标题
                        Row(modifier = Modifier.fillMaxWidth()) {
                            for (index in 0 until rowSize) {
                                val currentIndex = item * rowSize + index
                                Logger.e("RouterLayout ${item} <> ${currentIndex} ")
                                if (currentIndex >= routers.size) {
                                    TextIcon(
                                        icon = painterResource(id = com.atom.app.mvi.R.mipmap.icon_launcher),
                                        title = "NIL",
                                        modifier = Modifier
                                            .weight(1f)
                                            .size(100.dp)
                                    ) {
                                    }
                                }else{
                                    val current = routers[currentIndex]
                                    TextIcon(
                                        icon = painterResource(id = com.atom.app.mvi.R.mipmap.icon_launcher),
                                        title = current.router,
                                        modifier = Modifier
                                            .weight(1f)
                                            .size(100.dp)
                                    ) {
                                        Logger.e("RouterLayout  ${current}")
                                        nav.navigate(current.router)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        object Simple : Routers("Simple") {

            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                Column(modifier = Modifier) {
                    Text(text = router, fontSize = 50.sp)
                }
            }
        }

        object Simple1 : Routers("Simple1") {

            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                Text(text = router, fontSize = 60.sp)
            }
        }

        object Simple2 : Routers("Simple2") {

            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                Text(text = router, fontSize = 70.sp)
            }
        }

        object CustomView : Routers("CustomView") {
            fun Modifier.topBaseLine(
                baseLineToTop: Dp
            ): Modifier {
                return this.then(layout { measurable, constraints ->
                    val placeable = measurable.measure(constraints)
                    Logger.e(
                        measurable,
                        measurable.javaClass,
                        constraints,
                        constraints.javaClass,
                        placeable,
                        placeable.javaClass,
                        placeable.measuredWidth,
                        placeable.measuredHeight,
                        placeable.parentData
                    )
                    check(placeable[FirstBaseline] != AlignmentLine.Unspecified)
                    val firstBaseline = placeable[FirstBaseline]
                    val placeableY = baseLineToTop.roundToPx() - firstBaseline
                    val height = placeable.height + placeableY
                    layout(placeable.width, height) {
                        placeable.placeRelative(0, placeableY)
                    }
                })
            }

            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                Text(text = router, fontSize = 70.sp, modifier = Modifier.topBaseLine(200.dp))
            }
        }

        object CustomLayout : Routers("CustomLayout") {

            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                CustomLayout() {
                    Text(text = router, fontSize = 20.sp)
                    Text(text = router, fontSize = 30.sp)
                    Text(text = router, fontSize = 40.sp)
                    Text(text = router, fontSize = 50.sp)
                }
            }

            @Composable
            fun CustomLayout(
                modifier: Modifier = Modifier,
                // 此处可添加自定义的参数
                content: @Composable () -> Unit
            ) {
                Layout(
                    modifier = modifier, content = content
                ) { measurables, constraints ->
                    // 对 children 进行测量和放置
                    val placeables = measurables.map { measurable ->
                        // 测量每个 child 的尺寸
                        measurable.measure(constraints)
                    }
                    var yPosition = 0
                    val itemMaxHeight = constraints.maxHeight / placeables.size
                    layout(constraints.maxWidth, constraints.maxHeight) {
                        // 摆放 children
                        placeables.forEach { placeable ->
                            placeable.placeRelative(x = 0, yPosition)
                            yPosition += Math.max(placeable.height, itemMaxHeight)
                        }
                    }
                }
            }
        }

        object Spannable : Routers("Spannable", "一个类似TextView的SpannableString的使用") {

            @OptIn(ExperimentalFoundationApi::class)
            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                SpannableView(activity)
            }

            @Composable
            private fun SpannableView(activity: ComponentActivity) {
                val annotatedText = buildAnnotatedString {
                    append("Click ")
                    pushStringAnnotation(
                        tag = "URL",
                        annotation = "https://developer.android.com   111"
                    )
                    append("before")
                    pushStringAnnotation(
                        tag = "URL1",
                        annotation = "https://developer.android.com   222"
                    )
                    withStyle(
                        style = SpanStyle(
                            color = Color.Blue, fontWeight = FontWeight.Bold
                        )
                    ) {
                        append("here")
                    }
                    pop()
                    append("after")
                    pop()
                    withStyle(style = ParagraphStyle(lineHeight = 30.sp)) {
                        withStyle(style = SpanStyle(color = Color.Blue)) {
                            append("床前明月光，")
                        }
                        withStyle(
                            style = SpanStyle(
                                fontWeight = FontWeight.Bold, color = Color.Red
                            )
                        ) {
                            append("疑是地上霜。举头望明月，")
                        }
                        append("低头思故乡。")
                    }
                    append("--静夜思\n")
                }
                ClickableText(text = annotatedText, onClick = { offset ->
                    if (offset >= annotatedText.length) return@ClickableText
                    val get = annotatedText.get(offset)
                    Toast.makeText(activity, "" + get, Toast.LENGTH_SHORT).show()

                    val annotationList = annotatedText.getStringAnnotations(
                        tag = "URL", start = offset, end = offset
                    )
                    annotationList.forEach {
                        Log.e("ClickableText", it.item)
                    }
                    val annotationList2 = annotatedText.getStringAnnotations(
                        start = offset, end = offset
                    )
                    annotationList2.forEach {
                        Log.e("ClickableText", " >> " + it.item)
                    }
                })
            }

        }

        object Combined : Routers("Combined", "测试ComposeUI的双击滑动等事件的使用") {

            @OptIn(ExperimentalFoundationApi::class)
            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                ) {
                    Text(text = descriptor, fontSize = 30.sp, modifier = Modifier
                        .fillMaxWidth()
                        .combinedClickable(
                            onDoubleClick = {
                                Logger.e(" 1  double  onclick Spannable view")
                            }
                        ) {
                            Logger.e(" onclick Spannable view")
                        }
                        .pointerInput(Unit) {
                            detectTapGestures(
                                onDoubleTap = {
                                    Logger.e(" 2  double  onclick Spannable view")
                                }
                            )
                        })

                    Divider(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(2.dp), color = Color.Black
                    )

                    // combinedClickable 和 pointerInput 互斥 pointerInput的优先级高于 combinedClickable
                    Text(text = descriptor, fontSize = 30.sp, modifier = Modifier
                        .fillMaxWidth()
                        .combinedClickable(
                            onDoubleClick = {
                                Logger.e(" 1  double  onclick Spannable view")
                            }
                        ) {
                            Logger.e(" onclick Spannable view")
                        })

                }
            }
        }

        object Dialog : Routers("Dialog", "测试ComposeUI的使用Dialog") {

            @Composable
            fun Dialog(){
                val openDialog = remember { mutableStateOf(true) }
                if (openDialog.value) {
                    AlertDialog(
                        onDismissRequest = {
                            // 当用户点击对话框以外的地方或者按下系统返回键将会执行的代码
                            openDialog.value = false
                        },
                        title = {
                            Text(
                                text = "开启位置服务",
                                fontWeight = FontWeight.W700,
                                style = MaterialTheme.typography.h6
                            )
                        },
                        text = {
                            Text(
                                text = "这将意味着，我们会给您提供精准的位置服务，并且您将接受关于您订阅的位置信息",
                                fontSize = 16.sp
                            )
                        },
                        confirmButton = {
                            TextButton(
                                onClick = {
                                    openDialog.value = false
                                },
                            ) {
                                Text(
                                    "确认",
                                    fontWeight = FontWeight.W700,
                                    style = MaterialTheme.typography.button
                                )
                            }
                        },
                        dismissButton = {
                            TextButton(
                                onClick = {
                                    openDialog.value = false
                                }
                            ) {
                                Text(
                                    "取消",
                                    fontWeight = FontWeight.W700,
                                    style = MaterialTheme.typography.button
                                )
                            }
                        }
                    )
                }
            }
            @Composable
            override fun RouterLayout(
                activity: ComponentActivity,
                nav: NavHostController,
                entry: NavBackStackEntry
            ) {
                Dialog()
//                Column(modifier = Modifier.fillMaxSize()) {
//                    Button(onClick = {
//
//                    }) {
//                        Text(text = "Alertdialog" , fontSize = 20.sp)
//                    }
//                    Button(onClick = {
//
//                    }) {
//                        Text(text = "SystemDialog" , fontSize = 20.sp)
//                    }
//                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ContentView()
        }
    }

    @Preview
    @Composable
    fun PreView() {
        ContentView()
    }

    @Composable
    fun ContentView() {
        val navController = rememberNavController()

        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            Logger.e(controller, destination, arguments)
        }

        NavHost(
            navController = navController, startDestination = Routers.getMainRouter()
        ) {
            Routers.getRouters().forEach {
                composable(it.router) { entry ->
                    it.RouterLayout(this@MenuActivity, navController, entry)
                }
            }
        }
    }
}